import redis.asyncio as redis
from redis.exceptions import ConnectionError, TimeoutError

from collections import namedtuple

RedisConfig = namedtuple('RedisConfig', ['host', 'port', 'password', 'db', 'decode_responses', 'encoding'])


async def redis_connect(config: RedisConfig):
    
    redis_pool = redis.ConnectionPool(
        host=config.host,  # Redis服务器的地址
        port=config.port,  # Redis服务器的端口
        password=config.password,  # Redis服务器的密码
        db=config.db,  # Redis数据库的索引
        decode_responses=config.decode_responses, # 解码响应
        encoding=config.encoding # 编码请求
    )
    try:
        client = redis.Redis(connection_pool=redis_pool)
        if await client.ping():
            print("Redis connected")
        return client
    except (ConnectionError):
        raise Exception("Redis connection error")
    except (TimeoutError):
        raise Exception("Redis connect timeout")
    except Exception as e:
        raise Exception(f"Redis error: {e}")